package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.Category;
import com.itheima.domain.CategoryExample;
import com.itheima.domain.Movies;
import com.itheima.domain.MoviesExample;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.MoviesMapper;
import com.itheima.service.MoviesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.ref.PhantomReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MoviesServiceImpl implements MoviesService {

    @Autowired
    private MoviesMapper moviesMapper;

    @Override
    public PageInfo<Movies> findByPage(Integer pageNum, Integer pageSize, Integer cid, String keyword) {
        // 1.开启分页
        PageHelper.startPage(pageNum, pageSize);

        // 2.查询list
        MoviesExample moviesExample = new MoviesExample();

        // 动态sql拼接
        MoviesExample.Criteria criteria = moviesExample.createCriteria();
        if (cid != null) { // 分类id
            criteria.andCidEqualTo(cid);
        }

        if (keyword != null && keyword.length() > 0) {
            criteria.andKeywordLike("%" + keyword + "%");
        }

        // 时间降序
        moviesExample.setOrderByClause("show_time desc");
        List<Movies> list = moviesMapper.selectByExample(moviesExample);

        // 3.封装分页
        return new PageInfo<>(list);
    }

    @Override
    public void save(Movies movies) {
        moviesMapper.insertSelective(movies);
    }

    @Override
    public Movies findById(Integer id) {
        return moviesMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(Movies movies) {
        moviesMapper.updateByPrimaryKeySelective(movies);
    }

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Map<String, List<Movies>> findMoviesListMap() {
        // 0.声明返回map集合
        Map<String, List<Movies>> moviesListMap = new HashMap<>();
        // 1.查询所有分类
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("order_no desc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        // 2.遍历分类集合
        for (Category category : categoryList) {
            // 3.影视分页
            PageHelper.startPage(1, 6);
            // 4.根据分类id查询影视list
            MoviesExample moviesExample = new MoviesExample();
            moviesExample.createCriteria().andCidEqualTo(category.getId()); // where cid = ?
            moviesExample.setOrderByClause("show_time desc"); // order by show_time desc
            List<Movies> moviesList = moviesMapper.selectByExample(moviesExample);
            // 5.组装map
            moviesListMap.put(category.getCategoryName(), moviesList);
        }
        // 6.返回map
        return moviesListMap;
    }
}
